package org.opens.db.column.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.opens.db.JdbcUtil;
import org.opens.db.column.entity.ColumnEntity;
import org.opens.db.column.entity.TableEntity;
import org.opens.db.column.service.I_DbInfoService;
import org.opens.exception.BusinessException;
import org.opens.util.DatabaseConnectInfoEntity;

import java.util.List;

public class IDbInfoServiceOfMysql implements I_DbInfoService {

    private static final String typeMappingPath = "mapping\\MYSQL.json";

    @Override
    public List<TableEntity> getAllTables(DatabaseConnectInfoEntity databaseConnectInfo) {
        List<TableEntity> result = JdbcUtil.query(
                databaseConnectInfo,
                TableEntity.class,
                "select table_schema, table_name, table_comment from information_schema.TABLES where table_schema = ?;",
                databaseConnectInfo.getDatabaseName()
        );

        return result;
    }

    @Override
    public List<ColumnEntity> getAllColumn(DatabaseConnectInfoEntity databaseConnectInfo) {
        return JdbcUtil.query(
                databaseConnectInfo,
                ColumnEntity.class,
                "select table_schema, table_name, column_name, data_type, is_nullable, column_key, column_comment from information_schema.COLUMNS where table_schema = ? and table_name = ?;",
                databaseConnectInfo.getDatabaseName(),
                databaseConnectInfo.getTableName()
        );
    }

    @Override
    public TableEntity getTableInfo(DatabaseConnectInfoEntity databaseConnectInfo) {
        List<TableEntity> result = JdbcUtil.query(
                databaseConnectInfo,
                TableEntity.class,
                "select table_schema, table_name, table_comment from information_schema.TABLES where table_schema = ? and table_name = ?;",
                databaseConnectInfo.getDatabaseName(),
                databaseConnectInfo.getTableName()
        );

        if (CollectionUtil.isEmpty(result)) {
            throw new BusinessException("未查询到有效的数据, table_schema(" + databaseConnectInfo.getDatabaseName() + "), table_name(" + databaseConnectInfo.getTableName() + ").");
        }

        return result.get(0);
    }

}
